#include "config.h"
#include "sms_debug.h"

#include <time.h>
#include <stdarg.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>


static char *g_log_path = NULL;


const char *
get_log_path(void)
{
   return g_log_path;
}


static void
log_handler(const char *log_domain,   /* IN */
            GLogLevelFlags log_level, /* IN */
            const char *message,      /* IN */
            gpointer user_data)       /* IN */
{
   static char timestr[32];
   static glong oldSec = 0;
   GTimeVal curTime;
   FILE *logFile = (FILE *)user_data;
   char *logMsg;

   g_get_current_time(&curTime);
   if (curTime.tv_sec != oldSec) {
      time_t now;
      struct tm localNow;
      time(&now);
#ifdef HAVE_LOCALTIME_R
      localtime_r(&now, &localNow);
#else
      localNow = *localtime(&now);
#endif
      strftime(timestr, sizeof(timestr), "%b %d %H:%M:%S", &localNow);
      oldSec = curTime.tv_sec;
   }

   logMsg = g_strdup_printf("%s.%.03d: %s %d| %s\n", timestr,
                            (int)(curTime.tv_usec / 1000), g_get_prgname(),
                            (int)getpid(), message);

   if (logFile) {
      fprintf(logFile, "%s", logMsg);
      fflush(logFile);
   }

   if (log_level <= G_LOG_LEVEL_WARNING) {
       fprintf(stderr, "%s", logMsg);
   }

   g_free(logMsg);
}


static FILE *
open_log_posix(const char *tmplName, /* IN */
                      char **name)          /* OUT */
{
   GError *error = NULL;
   int fd;

   if (-1 != (fd = g_file_open_tmp(tmplName, name, &error))) {
      fprintf(stderr, "Using log file %s\n", *name);
      return fdopen(fd, "w");
   }
   fprintf(stderr, "Failed to open log: %s\n", error->message);
   g_error_free(error);
   return stderr;
}


gboolean
debug_open_log(void)
{
   char *name = NULL;
   char *tmplName;
   FILE *log;

   g_mkdir(g_get_tmp_dir(), 0700);
   tmplName = g_strdup_printf("%s-XXXXXX.log", PACKAGE_NAME);

   log = open_log_posix(tmplName, &name);

   g_log_set_default_handler(log_handler,
                             (log != stderr) ? log : NULL);

   g_log_path = name;

   g_free(tmplName);

   LINFO(0, ("Log for %s pid=%d version=%s", g_get_prgname(), (int)getpid(),
             VERSION));

   return (log != stderr);
}
